package com.aqelife.webflux.exceptions;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
 * 异常处理切面
 */
@ControllerAdvice
public class CheckAdvice {

    @ExceptionHandler(WebExchangeBindException.class)       // 调试获取异常
    public ResponseEntity<String> handleBindException(
            WebExchangeBindException e) {
        return new ResponseEntity<String>(toStr(e), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler({CheckException.class, RuntimeException.class})                 // 捕获自定义异常
    public ResponseEntity<String> handleCheckException(
            CheckException e) {
        return new ResponseEntity<String>(toStr(e), HttpStatus.BAD_REQUEST);
    }

    private String toStr(CheckException e) {
        return e.getFieldName() + ": 错误的值 " + e.getFieldValue();
    }


    // 把校验异常转换为字符串
    private String toStr(WebExchangeBindException ex) {
        return ex.getFieldErrors().stream()
                // 异常转字符串
                .map(e -> e.getField() + ":" + e.getDefaultMessage())
                // 数组多行数据转为一行(数组转字符串)
                .reduce("", (s1, s2) -> s1 + "\n" + s2);
    }

}
